package com.pdf.pdfserver.util;

import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Optional;

/**
 * @Author songfz
 * @Description PDF 首页封面工具类
 * @Date 2022/1/20
 */
public class PdfFrontCoverUtil {



    private static Logger LOG = LoggerFactory.getLogger(PdfFrontCoverUtil.class);

    /**
     * PDF 提取首页封面
     *
     * @param sourcePdf     PDF源文件
     * @param coverFullPath 封面全路径地址
     * @throws IOException
     */
    public static  void createFrontCover(File sourcePdf, String coverFullPath) {

        // load a pdf from a byte buffer
        FileOutputStream outputStream = null;
        RandomAccessFile raf = null;
        ByteBuffer buf = null;
        FileChannel channel = null;
        try {
            raf = new RandomAccessFile(sourcePdf, "r");
            channel = raf.getChannel();
            //这句代码通道建立了map映射,如果要删除file那么得接触映射
            buf = channel.map(FileChannel.MapMode.READ_ONLY,0, channel.size());
            PDFFile pdffile = new PDFFile(buf);
            if (pdffile.getNumPages() >= 1) {
                // draw the first page to an image
                PDFPage page = pdffile.getPage(1);
                Rectangle rect = new Rectangle(0, 0, (int) page.getBBox().getWidth(), (int) page.getBBox().getHeight());
                // generate the image
                Image img = page.getImage(rect.width, rect.height,
                        rect, // clip rect
                        null, // null for the imageobserver
                        true, // fill background with white
                        true // block until drawing is done
                );
                BufferedImage tag = new BufferedImage(rect.width, rect.height,
                        BufferedImage.TYPE_INT_RGB);
                tag.getGraphics().drawImage(img.getScaledInstance(rect.width, rect.height, Image.SCALE_SMOOTH), 0, 0, rect.width, rect.height, null);

                outputStream = new FileOutputStream(new File(coverFullPath));
                ImageIO.write(tag, "jpg", outputStream);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            Optional.ofNullable(outputStream).ifPresent(out-> {
                try {
                    out.close();
                } catch (IOException e) {
                    LOG.error(e.getMessage(),e);
                }
            });
            buf.clear();
            Optional.ofNullable(channel).ifPresent(fileChannel -> {
                try {
                    fileChannel.close();
                } catch (IOException e) {
                    LOG.error(e.getMessage(),e);
                }
            });
            Optional.ofNullable(raf).ifPresent(randomAccessFile -> {
                try {
                    randomAccessFile.close();
                } catch (IOException e) {
                    LOG.error(e.getMessage(),e);
                }
            });
        }

    }
}
